/**
 * Copyright 2016-2018 mobaas.com
 */
package com.mobaas.devops.notifier;

import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.json.JSONObject;

import com.mobaas.devops.Notifier;

/**
 * 钉钉机器人通知
 * @author billy zhang
 *
 */
public class DingTalkNotifier implements Notifier {
	
	private final String webhookApi = "https://oapi.dingtalk.com/robot/send?access_token=";
	
    private String atMobiles;
    private String msgtype = "markdown";

    public void notify(String title, String text, Map<String, Object> config) {
    		String accessToken = (String)config.get("accessToken");
    		
    		Map<String, Object> message = createMessage(title, text);
    		
    		JSONObject jsonObj = new JSONObject(message);
    		
    		CloseableHttpClient httpClient = HttpClients.createDefault();
    		try {
	    		HttpPost httpPost = new HttpPost(webhookApi + accessToken);
	    		httpPost.addHeader("Content-Type", "application/json");
	    		httpPost.setEntity(new StringEntity(jsonObj.toString(), "utf-8"));
	    		
	    		CloseableHttpResponse response = httpClient.execute(httpPost);
	    		
	    		response.close();
    		} catch (IOException ex) {
    			ex.printStackTrace();
    		} finally {
    			try {
				httpClient.close();
			} catch (IOException e) {
				e.printStackTrace();
			}
    		}
    }
    
    private Map<String, Object> createMessage(String title, String text) {
        Map<String, Object> messageJson = new HashMap<>();
        HashMap<String, String> params = new HashMap<>();
        params.put("text", text);
        params.put("title", title);
        //messageJson.put("dinggroup", this.dingGroup);
        messageJson.put("atMobiles", this.atMobiles);
        messageJson.put("msgtype", this.msgtype);
        messageJson.put(this.msgtype, params);
        return messageJson;
    }

    private String getAtMobilesString(String s) {
        StringBuilder atMobiles = new StringBuilder();
        String[] mobiles = s.split(",");
        for (String mobile : mobiles) {
            atMobiles.append("@").append(mobile);
        }
        return atMobiles.toString();
    }

}